package cn.net.ecode.modules.msg.test;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.activemq.transport.stomp.Stomp;
import org.apache.activemq.transport.stomp.Stomp.Headers.Subscribe;
import org.apache.activemq.transport.stomp.StompConnection;
import org.apache.activemq.transport.stomp.StompFrame;

import cn.net.ecode.common.mapper.JsonMapper;

public class StompSenderReceiver {
	
	/**
	 * 基于stomp协议
	 */
	public static void main(String[] args) throws Exception {
		
		String userId = "admin";
		
		// 连接服务
		StompConnection conn = new StompConnection();
		conn.open("127.0.0.1", 61613);
		conn.connect("system", "manager");
			
		// 发送JMS消息
		HashMap<String, String> txtHeaders = new HashMap<String, String>();
		txtHeaders.put(Stomp.Headers.Send.PERSISTENT, "true");
		String text = "消息内容.";
		String tx = UUID.randomUUID().toString().replaceAll("-", "");
		conn.begin(tx);
		conn.send(userId, text, tx, txtHeaders);
		conn.send(userId, text, tx, txtHeaders);
		conn.send(userId, text, tx, txtHeaders);
		conn.commit(tx);
		System.out.println("send: " + text);

		// 接受消息
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put(Stomp.Headers.TRANSFORMATION, "jms-stomp-map-json");
		conn.subscribe(userId, Subscribe.AckModeValues.AUTO, headers);

		try {
			
			while (true) {
				try {
					StompFrame msg = conn.receive(60000);
					String dataType = msg.getHeaders().get("dataType");
					String className = msg.getHeaders().get("className");
					String text2 = msg.getBody();
	
					if ("json".equals(dataType) && "java.util.Map".equals(className)) {
						Map<String, Object> map = JsonMapper.fromJsonString(text2, Map.class);
						System.out.println("received map: " + map);
					} else {
						System.out.println("received text: " + text2);
					}
	
					// 暂停 0.5 秒
					Thread.sleep(500);
				} catch (Exception e) {
					e.printStackTrace();
					break;
				}
			}
			
		}finally{
			
			conn.unsubscribe(userId);
			conn.disconnect();
			
		}

	}

}
